﻿using Clipboard.Model.Entities;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using  Clipboard.Model.Interface;
using Clipboard.Model.Interface;
using System.Diagnostics;

namespace Clipboard.Services
{
    public class SqlSugarHelper
    {


        public SqlSugarScope Db { get; }

        

        public SqlSugarHelper()
        {
            string connStr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
            Db = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connStr,
                    DbType = DbType.MySql, // 根据实际数据库类型修改，如 MySql, Oracle 等
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute
                },
                db =>
                {
                    //5.1.3.24统一了语法和SqlSugarScope一样，老版本AOP可以写外面
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //Debug.WriteLine(sql); //输出sql,查看执行sql 性能无影响

                        //获取原生SQL推荐 5.1.4.63  性能OK
                       // Debug.WriteLine(UtilMethods.GetNativeSql(sql, pars));

                        //获取无参数化SQL 对性能有影响，特别大的SQL参数多的，调试使用
                        //Debug.WriteLine(UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));
                    };
                }

            );



            Db.Aop.DataExecuting = (sql, entityInfo) =>
            {
                switch (entityInfo.OperationType)
                {
                    //执行insert时
                    case DataFilterType.InsertByObject:
                        //如果当前实体继承ICreatedTime就设置创建时间
                        if (entityInfo.EntityValue is ICreatedTime createdTime && createdTime.CreatedTime == DateTime.MinValue)
                        {
                            createdTime.CreatedTime = DateTime.Now;
                        }

                        if (entityInfo.EntityValue is IUpdatedTime updatedAt)
                        {
                            updatedAt.UpdatedTime = DateTime.Now;
                        }


                        break;
                    case DataFilterType.UpdateByObject:
                        if (entityInfo.EntityValue is IUpdatedTime updatedTime)
                        {
                            updatedTime.UpdatedTime = DateTime.Now;
                        }

                        break;
                    case DataFilterType.DeleteByObject:
                        break;
                }
            };


            // 调试 SQL 语句（可选）
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {
                // 打印 SQL 语句
                Console.WriteLine($"SQL 执行：{sql}");

                // 打印 SQL 参数
                if (pars != null && pars.Any())
                {
                    foreach (var param in pars)
                    {
                        Console.WriteLine($"参数名: {param.ParameterName}, 参数值: {param.Value}");
                    }
                }

                // 可选：打印执行的时间（单位：毫秒）
                var startTime = DateTime.Now;
                sql = sql.Replace("  ", " "); // 格式化 SQL 语句（去除多余空格）
                Console.WriteLine($"开始执行 SQL 语句：{sql}");

                // 捕获执行后的时间（可选）
                var endTime = DateTime.Now;
                var duration = endTime - startTime;
                Console.WriteLine($"SQL 执行时间：{duration.TotalMilliseconds}ms");
            };

        }
    }
}
